package com.zoe.app.listener;

import cn.hutool.core.thread.ThreadUtil;
import com.zoe.app.contextHolder.ContextHolder;
import com.zoe.app.event.ZoeEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author Zoe.Zhang
 * @date 2022/02/08
 * @description 接口的泛型如果不指定, 那么所有spring容器中的事件都会变监听到, 如果指定了泛型, 那么只会监听指定的事件
 */
@Component
public class ZoeEventListener implements ApplicationListener<ZoeEvent> {
    private static final Logger logger = LoggerFactory.getLogger(ZoeEventListener.class);

    @Override
    @Async // 开启异步的话, ThreadLocal就获取不到值了, 因为不是在一个线程里面了
    public void onApplicationEvent(ZoeEvent zoeEventSource) {
        String msg = ContextHolder.getMsg();
        System.out.println(msg + "   ZoeEventListener   " + Thread.currentThread().getName());
        // 获取发送事件的类
        Object source = zoeEventSource.getSource();
        logger.error(source.toString());
        // 获取发送事件时候绑定的消息
        String message = zoeEventSource.getShutDown();
        logger.error(message);

        ThreadUtil.sleep(5 * 1000); // 线程睡眠 5 秒
        ContextHolder.removeMsg();
    }
}
